package org.xq.shop.maxaishop.consumer;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xq.shop.maxaishop.entity.XqCorder;
import org.xq.shop.maxaishop.service.XqCorderService;
import sy.mqapi.Consumer;
import sy.mqapi.MsgListener;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单监听接口
 */
@Slf4j
@Service
public class MyOrderConsumer implements MsgListener {
    @Value("${mq.host}")
    private String host;    //MQ Broker 地址
    @Value("${mq.port}")
    private int port;       //MQ Broker 端口号
    //MQ主题
    private String topic = "topicOrder";
    @Resource
    private XqCorderService xqCorderService;
    //线程池
    private ExecutorService executorService = Executors.newCachedThreadPool();

    @PostConstruct
    public void initConsumer() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Consumer consumer = null;
                try {
                    consumer = new Consumer(host, port, "cons1", "group1", topic, MyOrderConsumer.this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static final AtomicLong msgCounter = new AtomicLong();
    /**
     * 处理消息
     * @param topic 主题
     * @param msg 消息
     * @throws Exception
     */
    @Override
    public void onMsg(String topic, String msg) throws Exception {
        //JSON消息转订单对象
        XqCorder xqCorder = JSON.parseObject(msg, XqCorder.class);

        long counter = msgCounter.incrementAndGet();
        boolean success = xqCorderService.createOrder(xqCorder);
        if (success)
            log.info("已成功下订单! count:{} name: {}",counter, xqCorder.getCustomername());
        else
            log.info("下单失败! count:{} name: {}",counter, xqCorder.getCustomername());
    }
}
